/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Servlets;

import EntityPackage.Agenzia;
import EntityPackage.BusinessLogic;
import EntityPackage.Location;
import EntityPackage.Menu;
import EntityPackage.Piatto;
import EntityPackage.Prenotazione;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author work
 */
public class Booking extends HttpServlet {
    @EJB
    private BusinessLogic businessLogic;
    HttpSession session;
    

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            RequestDispatcher rd;
            session = request.getSession();
            switch (request.getParameter("hidden")) {
                case "prenota":                                   
                    if(session.getAttribute("logged").equals("true"))                     
                        response.sendRedirect("prenotazioneIndex.jsp");
                    else
                        response.sendRedirect("index.jsp");                                                               
                    break;
                case "data":
                    session.setAttribute("data", request.getParameter("data"));
                    if(request.getParameter("ora").equals("12:00") || request.getParameter("ora").equals("13:00") || request.getParameter("ora").equals("14:00"))
                        session.setAttribute("fascia", "Pranzo");
                    else if(request.getParameter("ora").equals("18:00") || request.getParameter("ora").equals("19:00"))
                        session.setAttribute("fascia", "Aperitivo");
                    else 
                        session.setAttribute("fascia", "Cena");
                    session.setAttribute("ora", request.getAttribute("ora"));
                    response.sendRedirect("prenotazioneLoc.jsp");
                    break;
                case "location":
                    Date date = Date.valueOf((String)session.getAttribute("data"));
                    Calendar cdata1 = Calendar.getInstance();
                    cdata1.setTime(date);
                    cdata1.add(Calendar.DAY_OF_MONTH, 1);
                    Calendar cdata2 = Calendar.getInstance();
                    cdata2.setTime(date);
                    cdata2.add(Calendar.DAY_OF_MONTH, -1);
                    Location l = businessLogic.findLocationById(Integer.parseInt((String)request.getParameter("location")));             
                    Iterator<Prenotazione> i = l.getPrenotazioneCollection().iterator();
                    boolean found = false;
                    Calendar pdata = Calendar.getInstance();
                    while(i.hasNext() && !found){
                        pdata.setTime(i.next().getData());
                        if(pdata.after(cdata2) && pdata.before(cdata1))
                            found = true;
                    }
                    if(found){
                        out.println("<script>alert('Location non disponibile in quella data!');</script>");
                        response.sendRedirect("prenotazioneLoc.jsp");
                    }else{
                        session.setAttribute("location", l.getIdLocation());
                        request.setAttribute("agenzieList",businessLogic.findAllAgenzia());
                        rd = getServletContext().getRequestDispatcher("/prenotazioneAg.jsp");
                        rd.forward(request, response);
                    }
                    break;
                case "agenzia":
                    date = Date.valueOf((String)session.getAttribute("data"));
                    cdata1 = Calendar.getInstance();
                    cdata1.setTime(date);
                    cdata1.add(Calendar.DAY_OF_MONTH, 1);
                    cdata2 = Calendar.getInstance();
                    cdata2.setTime(date);
                    cdata2.add(Calendar.DAY_OF_MONTH, -1);
                    Agenzia a = businessLogic.findAgenziaById(Integer.parseInt((String)request.getParameter("agenzia")));             
                    i = a.getPrenotazioneCollection().iterator();
                    found = false;
                    pdata = Calendar.getInstance();
                    while(i.hasNext() && !found){
                        pdata.setTime(i.next().getData());
                        if(pdata.after(cdata2) && pdata.before(cdata1))
                            found = true;
                    }
                    if(found){
                        response.sendRedirect("prenotazioneAg.jsp");
                        out.println("<script>alert('Agenzia non disponibile in quella data!');</script>");
                    }else{
                        session.setAttribute("agenzia", Integer.parseInt(request.getParameter("agenzia")));
                        session.setAttribute("piatti",businessLogic.findAllPiatto());
                        response.sendRedirect("prenotazioneMenu.jsp");
                    }
                    break;
                case "menu":
                    if(request.getParameter("menu").equals("4")){
                        request.setAttribute("piatti",businessLogic.findAllPiatto());
                        rd = getServletContext().getRequestDispatcher("/menuPers.jsp");
                        rd.forward(request, response);
                    }else{
                        session.setAttribute("menu", Integer.parseInt(request.getParameter("menu")));
                        response.sendRedirect("pagamento.jsp");}
                    break;
                case "menu2":
                    Menu menu = new Menu();
                    List<Piatto> checked = new ArrayList();
                    List<Piatto> all = businessLogic.findAllPiatto();
                    Iterator<Piatto> it = all.iterator();
                    while(it.hasNext()){
                        Piatto p = it.next();
                        if(request.getParameter(p.getIdPiatto()+"") != null)
                            checked.add(p);                       
                    }
                    menu.setPiattoCollection(checked);
                    businessLogic.addMenu(menu);
                    session.setAttribute("menu", menu.getIdMenu());
                    response.sendRedirect("pagamento.jsp");
                    break;
                case "finito":
                    Prenotazione p = new Prenotazione(businessLogic.findMenuById((int)session.getAttribute("menu")),
                                                      businessLogic.findLocationById((int)session.getAttribute("location")),
                                                      businessLogic.findClientById((int)session.getAttribute("id")),
                                                      businessLogic.findAgenziaById((int)session.getAttribute("agenzia")));
                    p.setData(Date.valueOf((String)session.getAttribute("data")));
                    p.setOra(Time.valueOf((String)session.getAttribute("ora")));
                    /*out.println("<html>");
                    out.println("<body>");             
                    out.println(p.getData()+" "+p.getOra()+" "+p.getLocation().getIdLocation()+" "+p.getMenu().getIdMenu()+" "+p.getAgenzia().getIdAgenzia()+" "+p.getCliente().getIdCliente());              
                    out.println(businessLogic.addPrenotazione(p));
                    out.println("</body>");
                    out.println("</html>");*/
                    break;
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
